package com.shujia.flink.kafka;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Demo01KafkaConsumer {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        KafkaSource<String> kafkaSource = KafkaSource
                .<String>builder() // 指定Kafka中每条数据的格式
                .setBootstrapServers("master:9092,node1:9092,node2:9092") // 设置Kafka集群的地址
                .setTopics("bigdata") // 指定Topic
                .setGroupId("my-group-0") // 指定消费者组ID
                // 设置初始的偏移量 earliest：从最早开始消费  latest：从最新的消息开始消费
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new SimpleStringSchema()) // 指定如何去解析Kafka中过来的每一条数据
                .build();

        // 默认情况下Kafka Source的并行度等于Topic的分区数
        DataStreamSource<String> kafkaDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource");

        kafkaDS.print();

        env.execute();
    }
}
